<template>
  <div class="login-container">
    <el-form class="login-from" ref="login-form" :model="user" :rules="fromRules">
      <div class="login-title">
        <span>资讯后台管理系统</span>
      </div>
      <el-form-item prop="username">
        <el-input v-model="user.username" placeholder="请输入账号"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="user.password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item prop="agree">
        <el-checkbox v-model="user.agree">我已同意相关条款</el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button class="login-btn" type="primary" :loading="loginLoading" @click="onLogin">登录</el-button>
        <el-button class="login-btn" type="primary" style="margin-left: -0px;" @click="onRegister()">注册</el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-dialog title="用户注册" :visible.sync="addDialogVisible" width="500px" append-to-body>
        <el-form :model="temp" ref="addForm" label-width="90px" @submit.native.prevent>
          <el-form-item label="用户名" prop="username">
            <el-input placeholder="请输入用户名" v-model="temp.username" clearable>
            </el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input placeholder="请输入密码" v-model="temp.password" clearable>
            </el-input>
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-select v-model="temp.gender" placeholder="请选择">
              <el-option label="男" :value="0"></el-option>
              <el-option label="女" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input placeholder="请输入联系电话" v-model="temp.phone"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input placeholder="请输入邮箱" v-model="temp.email"></el-input>
          </el-form-item>
          <el-form-item label="用户角色" prop="role_id">
            <el-select v-model="temp.role_id" placeholder="请选择">
              <el-option label="管理员" :value="2"></el-option>
              <el-option label="作者" :value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click.once="addUser()">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { userLogin } from '@/api/user'
import axios from "axios"
import eventBus from '@/utils/global-bus'

export default {
  name: "LoginIndex",
  data() {
    return {
      user: {
        username: '',
        password: null,
        agree: true, //是否同意协议选中
      },
      addDialogVisible: false,
      addForm: '',
      temp: {
        username: '',
        password: '',
        gender: '',
        phone: '',
        email: '',
        role_id: null
      },
      loginLoading: false, //登录的loading状态
      fromRules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '验证码不能为空', trigger: 'blur' },
          { pattern: /^\d{6}$/, message: '请输入正确的验证码格式', trigger: 'blur' }
        ],
        // 自定义验证
        agree: [
          {
            validator: (rule, value, callback) => {
              if (value) {
                callback()
              } else {
                callback(new Error('请同意协议'))
              }
            }, trigger: 'blur'
          },
        ]
      }
    }
  },
  methods: {
    onLogin() {
      this.$refs['login-form'].validate((valid) => {
        //验证失败，停止提交 
        if (!valid) {
          return
        }
        this.login()
      });
    },
    onRegister() {
      this.addDialogVisible = true;
    },
    addUser() {
      let params = {
        username: this.temp.username,
        password: this.temp.password,
        gender: this.temp.gender,
        phone: this.temp.phone,
        email: this.temp.email,
        role_id: this.temp.role_id
      }
      console.log(params, 'params');
      axios.post('http://127.0.0.1/register', params).then(res => {
        console.log(res, 'res');
        if (res.status === 200) {
          if (res.data.message === '') {
            this.$message({
              type: 'success',
              message: '添加成功!'
            });
            this.addDialogVisible = false;
            this.clearAddForm();
          } else {
            this.$message({
              type: 'error',
              message: "用户名已经存在!"
            });
          }
        }

      }).catch(err => {
        console.log("获取数据失败" + err);
        this.$message({
          type: 'success',
          message: '添加失败!'
        });
      })
    },
    clearAddForm() {
      this.temp = {
        bulid_name: "",
        head_name: "",
        sex: "",
        phone: null,
      }
    },
    login() {
      this.loginLoading = true
      // 验证通过，提及表单
      userLogin(this.user.username, this.user.password).then((res) => {
        if (!res.success) {
          this.$message.error('登录失败,手机号或验证码失败');
          this.loginLoading = false
        } else {
          console.log(res.Token, 'res');
          // 登录成功
          this.loginLoading = false
          this.$message({
            message: '登录成功',
            type: 'success'
          });
          eventBus.$emit('sendUsername', this.user.username)
          localStorage.setItem('user', JSON.stringify(res.Token))
          localStorage.setItem('username', JSON.stringify(this.user.username))
          localStorage.setItem('userid', JSON.stringify(this.user.id))
          // 跳转到home首页
          this.$router.push({
            name: 'home'
          })
        }
      })
    },
  }
}
</script>
<style lang="less">
.login-title {
  text-align: center;
  position: relative;
  top: -30px;
  font-size: 20px;
}

.login-container {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: url('../../assets/login/login_backImg.jpeg') no-repeat;
  background-size: cover;
}

.login-from {
  background-color: #fff;
  padding: 50px;
  min-width: 300px;
}

.login-btn {
  width: 100%;
  margin-bottom: 10px;
}

.register-btn {
  width: 100%;
  margin-bottom: 10px;
}
</style>